package org.example.service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.PutObjectRequest;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.AllArgsConstructor;
import lombok.extern.java.Log;
import org.example.bean.Banner;
import org.example.bean.Category;
import org.example.configs.OssConfig;
import org.example.dao.BannerMapper;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.util.List;
import java.util.UUID;

@Service
@AllArgsConstructor
@Log
public class BannerServiceImpl implements BannerService {
    //配合上面的@AllArgsConstructor
    private final BannerMapper bannerMapper;
    private final OssConfig ossConfig;
    private final OSS ossClient;
    @Override
    @Transactional //添加事务
    //当新增货修改了轮播图时，需要清楚所有相关的缓存
    //“banner” :是缓存的名称
    //allEntries = true : 表示清除所有的缓存
    @CacheEvict(value = "banners",allEntries = true) //添加缓存清除
    //只要添加了轮播图，就需要清除缓存
    public Banner addBanner(Banner banner) {
        //第一步上传图片到Oss
        String originalFilename = banner.getImageFile().getOriginalFilename();//文件名
        String fileExtension="";//文件扩展名
        if(originalFilename.contains(".")&&originalFilename!=null){
            fileExtension=originalFilename.substring(originalFilename.lastIndexOf("."));
        }
        System.out.println("原文件名："+originalFilename+"\t扩展名"+fileExtension);
        String objectKey="files/"+ UUID.randomUUID().toString()+fileExtension; //保存的对象在oss中的地址
        PutObjectRequest putObjectRequest=null;
        try {
            putObjectRequest = new PutObjectRequest(ossConfig.getBucketName(), objectKey, banner.getImageFile().getInputStream());
            ossClient.putObject(putObjectRequest);   //上传到Oss

            String fileUrl = ossConfig.getUrlPrefix() + File.separator + objectKey;
            banner.setImage_url(fileUrl);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("上传文件到OSS失败"+ e.getMessage());
            throw new RuntimeException("上传文件到OSS失败"+e.getMessage());
        }

        //第二步保存图片到数据库
        bannerMapper.insert(banner);
        return banner;
    }

    //根据状态获取缓存

    @Override
    //启用缓存：
    //value="banners" : 缓存的名称，所有轮播图相关的缓存都存放在这个命名空间下
    //key="#bannerStatus!=null ? 'status_'+#bannerStatus : 'all'" : 缓存的key，这里使用bannerStatus作为key，因为根据状态查询轮播图是一个固定的操作，所以可以缓存
    //  - 如果bannerStatus为null，缓存的key为"all"，表示查询所有轮播图
    //  - 如果bannerStatus不为null，缓存的key为"status_"+bannerStatus，例如status_1表示查询状态为1的轮播图
    //这个策略可以区分不同状态的轮播图列表，同时也有一个缓存所有轮播图的入口，例如status_1和status_2的轮播图是不同的，所以可以缓存
    //key使用了spring el表达式，根据bannerStatus是否为null来动态生成key
    //condition="#bannerStatus != null" : 缓存的条件，只有当bannerStatus不为null时才缓存
    @Cacheable(value = "banners", keyGenerator = "BannerKeyGenerator")
    public List<Banner> getBannersByStatus(Integer bannerStatus) {
        LambdaQueryWrapper<Banner> queryWrapper = new LambdaQueryWrapper<>();
        if (bannerStatus!=null && bannerStatus!=-1){
            queryWrapper.eq(Banner::getBanner_status, bannerStatus);
        }
        return bannerMapper.selectList(queryWrapper);
    }
    @CacheEvict(value = "banners",allEntries = true)
    @Transactional
    public boolean updateBannerStatus(Integer bannerId, Integer bannerStatus) {
        Banner banner = this.bannerMapper.selectById(bannerId);
        if(banner==null){
            throw new RuntimeException("轮播图不存在"+bannerId);
        }
        banner.setBanner_status(bannerStatus);
        this.bannerMapper.updateById(banner);
        return true;
    }
}
